package com.bw.utils.excel;

import com.microsoft.schemas.office.visio.x2012.main.CellType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtil {

    public static List<Map> readExcel(String ext, InputStream inputStream) throws IOException {//读取excel工具类
        List<Map> list=new ArrayList<>();

        Workbook wb=null;

        if(".xls".equals(ext)){
            wb=new HSSFWorkbook(inputStream); //获取excel对象 03 xls
        }
        if(".xlsx".equals(ext)){
            wb=new XSSFWorkbook(inputStream);//获取excel对象 07 xlsx
        }

        Sheet sheet = wb.getSheetAt(0);//获取第一个sheet页

       int rowNum =  sheet.getLastRowNum();//获取数据行号

        for (int i=2;i<=rowNum;i++){
          Row row =  sheet.getRow(i);//读取某一行的数据
          Map map=new HashMap();
         int cellNum = row.getLastCellNum();//获取列的数量
          for (int j=0;j<cellNum;j++){
              String key=getDataKey(sheet.getRow(1).getCell(j));//获取第二行每一列的数据
              Object value=getDataValue(row.getCell(j));//获取当前行每一列的数据
              map.put(key,value);
          }
          list.add(map);
        }
        return list;
    }

    public static String getDataKey(Cell cell){
        return cell.getStringCellValue();
    }

    public static Object getDataValue(Cell cell){
        if(null==cell){
            return null;
        }

       int cellType =  cell.getCellType(); //获取当前单元格的类型

        Object value=null;
        switch (cellType){
            case Cell.CELL_TYPE_STRING:
                value = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                 value = null;
                 break;
            case Cell.CELL_TYPE_BOOLEAN:
                 value = cell.getBooleanCellValue();
                 break;
            case Cell.CELL_TYPE_NUMERIC:
                if(DateUtil.isCellDateFormatted(cell)){
                    value = cell.getDateCellValue();
                }else {
                    value = cell.getNumericCellValue();
                }
                break;
        }

        return value;
    }

}
